package one.stand.util;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.math.NumberUtils;

import java.util.List;
import java.util.Objects;
import java.util.function.Function;

/**
 * @author cjr
 */
public class SqlUtil {

    public static String securitySql(String sql) {
        if (StringUtils.isBlank(sql)) {
            return sql;
        }

        String s = sql.replaceAll(";", StringUtils.SPACE);
        s = s.replaceAll("1=1", StringUtils.SPACE);
        s = s.replaceAll("and", StringUtils.SPACE);
        s = s.replaceAll("or", StringUtils.SPACE);
        return s;
    }

    public static <T> String in(List<T> ids) {
        String inSql = in(ids, type -> type);
        return securitySql(inSql);
    }

    public static <T, R> String in(List<T> ids, Function<T, R> function) {
        if (OneListUtil.isEmpty(ids)) return null;
        StringBuilder stringBuilder = new StringBuilder();
        Boolean isNum = null;
        for (T t : ids) {
            R id = function.apply(t);
            if (Objects.isNull(id)) {
                continue;
            }
            if (Objects.isNull(isNum)) {
                isNum = NumberUtils.isCreatable(String.valueOf(id));
            }
            if (isNum) {
                stringBuilder.append(",").append(id);
            } else {
                stringBuilder.append(",").append("'").append(id).append("'");
            }
        }
        String inSql = stringBuilder.length() > 0 ? stringBuilder.substring(1) : null;
        return securitySql(inSql);
    }

    public static String like(String search) {
        return StringUtils.isNoneBlank(search) ? "%" + search + "%" : null;
    }

    public static String likeLeft(String search) {
        return StringUtils.isNoneBlank(search) ? "%" + search : null;
    }

    public static String likeRight(String search) {
        return StringUtils.isNoneBlank(search) ? search + "%" : null;
    }
}
